<template>
    <div>
        <queryView v-model="queryParams" @query="getListData(1)" @create="handleCreate" />
        <el-card shadow="hover">
            <el-table v-loading="tableDataLoading" :data="tableData" table-layout="auto">
                <el-table-column align="center" type="index" label="#" min-width="50" />
                <el-table-column align="center" prop="cn_name" label="角色名称" />
                <el-table-column align="center" prop="name" label="角色标识">
                    <template #default="scope">
                        <el-tag type="warning">{{ scope.row.name }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="created_at" width="300" label="创建时间" />
                <el-table-column align="center" prop="note" label="备注" min-width="300" />
                <el-table-column align="center" fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleEdit(scope.row)"> 编辑 </el-button>
                        <el-button link type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 20px">
                <el-pagination
                    v-model:current-page="page"
                    v-model:page-size="pageSize"
                    @update:current-page="getListData()"
                    @update:page-size="getListData()"
                    layout="total,sizes,prev, pager, next,jumper"
                    size="small"
                    background
                    :page-sizes="[20, 50, 100, 200, 500]"
                    :total="total" />
            </div>
            <!-- 弹窗 -->
            <el-dialog
                v-model="dialogFormVisible"
                :title="formIsEdit ? '编辑' : '新增'"
                width="550px"
                destroy-on-close
                :close-on-click-modal="false">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                    <el-form-item label="角色名称" prop="cn_name">
                        <el-input v-model="form.cn_name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="角色标识" prop="name">
                        <el-input v-model="form.name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="菜单权限" prop="status">
                        <div class="menu-tree" style="border: 1px solid #eee; width: 100%; padding: 10px">
                            <el-tree
                                ref="menuTreeRef"
                                style="max-width: 600px"
                                :data="options.menus"
                                :default-checked-keys="form.menu_ids"
                                show-checkbox
                                :check-strictly="true"
                                node-key="id"
                                empty-text="加载中，请稍候"
                                :props="{
                                    children: 'children',
                                    label: 'title'
                                }" />
                        </div>
                    </el-form-item>
                    <el-form-item label="备注" prop="note" style="">
                        <el-input type="textarea" :rows="3" v-model="form.note" placeholder="请输入备注" autocomplete="off" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="handleSubmit(formRef)">确 定</el-button>
                    </div>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup lang="ts">
    // import { apiRole } from '@/api/test'
    import { apiRole, getRoleOptions, getRoleMenuId } from '@/api/restful'
    import type { ComponentSize, FormInstance, FormRules, ElTree } from 'element-plus'
    import type { Role } from '@/types/global'
    import ymiUpload from '@/components/ymi/ymiUpload.vue'
    import queryView from './queryView.vue'
    const total = ref(0)
    const page = ref(1)
    const pageSize = ref(20)
    const options = ref<any>({})
    const tableDataLoading = ref(true)
    const tableData = ref<Role[]>([])
    const queryParams = ref({})

    const menuTreeRef = ref<InstanceType<typeof ElTree>>()

    const dialogFormVisible = ref(false)
    const formRef = ref<FormInstance>()
    const formIsEdit = ref(false)
    const form = ref<Role>({
        id: '',
        // status: 1,
        name: '',
        cn_name: '',
        menu_ids: []
    })
    const rules = reactive<FormRules<Role>>({
        name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        slug: [{ required: true, message: '请输入角色标识', trigger: 'blur' }]
    })
    onMounted(() => {
        getRoleOptions({}).then((res) => {
            console.log(res.data)
            options.value = res.data
        })
        getListData()
    })

    /**
     * 获取列表数据
     */
    const getListData = (nowPage?: number) => {
        console.log('getListData', nowPage)
        tableDataLoading.value = true
        if (nowPage) page.value = nowPage
        const paramsData = {
            ...{ page: page.value, pageSize: pageSize.value },
            ...queryParams.value
        }
        apiRole(paramsData, 'GET')
            .then((res) => {
                console.log(res.data?.data)
                tableDataLoading.value = false
                tableData.value = res.data?.data
                total.value = res.data?.total
            })
            .catch(() => {
                tableDataLoading.value = false
            })
    }
    const handleCreate = () => {
        formIsEdit.value = false
        form.value = {} as Role
        dialogFormVisible.value = true
    }

    /**
     * 处理表单提交
     * @param formEl
     */
    const handleSubmit = async (formEl: FormInstance | undefined) => {
        form.value.menu_ids = getMenuAllCheckedKeys() as number[]
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (!valid) return
            dialogFormVisible.value = false
            if (formIsEdit.value) {
                updateRequest(form.value, '保存成功')
                return
            }
            apiRole(form.value, 'POST').then((res) => {
                ElMessage({
                    type: 'success',
                    message: '新增成功'
                })
                getListData()
            })
        })
    }
    /**
     * 获取菜单选中节点
     */
    const getMenuAllCheckedKeys = () => {
        // 目前被选中的菜单节点
        const checkedKeys = menuTreeRef.value?.getCheckedKeys() || []
        // 半选中的菜单节点
        const halfCheckedKeys = menuTreeRef.value?.getHalfCheckedKeys() || []
        checkedKeys.unshift(...halfCheckedKeys)
        // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
        return checkedKeys
    }
    /**
     * 删除
     */
    const handleDelete = (id: number) => {
        ElMessageBox.confirm('确认删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            apiRole({ id }, 'DELETE').then((res) => {
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                })
                getListData()
                console.log(res)
            })
        })
    }
    /**
     * 编辑
     */
    const handleEdit = (row: Role) => {
        console.log(row)
        form.value = { ...row }
        getRoleMenuId({ id: row.id }).then((res) => {
            console.log(res)
            form.value.menu_ids = res.data as []
            // row.menu_ids = res.data as []
        })

        formIsEdit.value = true
        dialogFormVisible.value = true
    }
    /**
     * 更新请求
     * @param params
     * @param msg
     */
    const updateRequest = (params: any, msg = '更新成功') => {
        apiRole(params, 'PUT').then((res) => {
            ElMessage({
                type: 'success',
                message: msg
            })
            getListData()
        })
    }
    /**
     * 处理表格数据switch事件
     * @param value
     * @param id
     */
    const handleSwitchChange = (value: any, id: number) => {
        updateRequest({ id, status: value }, '更新成功')
    }
</script>

<style></style>
